#!/usr/bin/env python
import os
from argparse import ArgumentParser

from testlib.overscan import do_overscan
from testlib.stack import stack_image
from testlib.utils import make_dir, remove_dir
from testlib.imgconfig import load_imgconfig


def run(flist, outname, oscan=False, confname=None, fbias=None, nclip=None):
    if oscan:
        imgconf = load_imgconfig(confname)
        dname = os.path.dirname(outname)
        if dname == '':
            dname = '.'
        tmpdir = '{}/tmp'.format(dname)
        if os.path.exists(tmpdir):
            raise Exception('temporary directory already exists: {}'.format(tmpdir))
        make_dir(tmpdir)
        flist = do_overscan(flist, imgconf, outdir=tmpdir)
        if fbias is not None:
            fbias = do_overscan([fbias, ], imgconf, outdir=tmpdir)[0]
        stack_image(flist, outname, fbias=fbias, nclip=nclip)
        remove_dir(tmpdir)
    else:
        stack_image(flist, outname, fbias=fbias, nclip=nclip)


def main():
    parser = ArgumentParser()
    parser.add_argument('names', nargs='*', type=str)
    parser.add_argument('--outname', '-o', type=str, required=True)
    parser.add_argument('--oscan', '-x', action='store_true')
    parser.add_argument('--configure', '-c', type=str, default=None)
    parser.add_argument('--bias', '-b', type=str, default=None)
    parser.add_argument('--nclip', '-n', type=int, default=None)
    args = parser.parse_args()
    run(args.names, args.outname, oscan=args.oscan, confname=args.configure, fbias=args.bias, nclip=args.nclip)


if __name__ == '__main__':
    main()
